#coding=utf8
#LightCam 处理snmpinterface.txt程序
#init by hfh 20150608

import time,re,sys,traceback,threading,pymongo,json
import lc_libs

if __name__ == "__main__":


	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()

	try:
		#初始化数据库
		db=lc_libs.lc_mongodb_operater('127.0.0.1',27017)

		db.connect()
		Conn=db.getConn()
		if Conn==None:
			print "Can not Connect to the MondbDB"
			exit(0)
		
		perf_dbname='lc_perf'
		snmpinterface_tablename='lc_vipport'
		
		perf_db=db.useDatabase(perf_dbname)
		snmpinterface_table=db.UseCollection(perf_db,snmpinterface_tablename)

	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" 初始化数据库失败:\n"+excinfo+"\n")
		logfile.flush()
		exit(0)
		
	timelist=['08:00','08:30','09:00','09:30','10:00','10:30','11:00','11:30','12:00','12:30','13:00','13:30','14:00','14:30','15:00','15:30','16:00','16:30','17:00']
	#i=0
	
	portlist=[
		['172.26.254.141','Gi5/6'],
		['172.26.254.142','Gi5/6'],
		['172.26.254.31','Gi5/5'],
		['172.26.254.31','Gi5/6'],
		['172.26.254.32','Gi5/5'],
		['172.26.254.32','Gi5/6'],
		['172.26.254.33','Gi5/5'],
		['172.26.254.33','Gi6/5'],
		['172.26.254.34','Gi5/5'],
		['172.26.254.34','Gi6/5'],
		['172.26.254.37','Gi5/3'],
		['172.26.254.38','Gi5/3'],
		['172.26.254.53','Gi1/46'],
		['172.26.254.54','Gi1/46'],
		['172.26.254.7','Gi1/48'],
		['172.26.254.8','Gi1/48']
	]
	
	while True:
		time.sleep(1)

		jdata=[]
		for line in portlist:
			
			Device=line[0]
			ifName=line[1]
			name="%s %s" % (Device,ifName)
			
			rowdata=[]
			expr={"Device":Device,"ifName":ifName}
			sortcont=[("Time",pymongo.ASCENDING)]
			opts=db.queryData(snmpinterface_table,expr,sortcont,200)
			res=db.genResult(opts)
			for line in res:
				rowdata.append(float(line['RateInOctets']))
			jdata.append({'name':name,'data':rowdata})
		
		print json.dumps(jdata)
		file=open(lchome+"/pyweb/static/json/vipport/lc_vipport.json",'w')
		file.write(json.dumps(jdata))
		file.close()
		
		file=open(lchome+"/pyweb/static/json/vipport/lc_vipport_time.json",'w')
		file.write(json.dumps(timelist))
		file.close()
		
		#print json.dumps(jdata)
